<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\TaskTemplate as TaskTemplateModer;
use app\admin\model\TaskCategory;
use app\admin\model\PayConfig;
use app\admin\model\TaskImgs;
use app\admin\model\TaskCategoryList;
use app\admin\model\Shop;
use app\admin\model\Area;
use app\admin\model\User;
use app\admin\model\DistributeTask;
use think\Db;
use think\Exception;
use think\facade\Request;

/**
 * 任务管理
 *
 * @icon   fa fa-list
 */
class TaskTemplate extends Backend
{

    protected $model = null;
    protected $categorylist = [];
    protected $noNeedRight = ['selectpage'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new TaskTemplateModer();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $zi = $this->request->request('zi','');
        $this->assignconfig('zi', $zi);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as &$v) {
                $v['category_name'] = TaskCategory::where(['id'=>$v['category_id']])->value('name');        

                // $variate = json_decode($v['variate'],true);
                // foreach ($variate as $key => &$value) {
                //     $value['variate_value'] = str_replace(',',';',$value['variate_value']);
                // }
                // $v['variate'] = json_encode($variate,JSON_UNESCAPED_UNICODE);
                // $this->model->where(['id'=>$v['id']])->update(['variate'=>$v['variate']]);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $user_list =  User::field("nickname,id")->where(['is_task'=>1])->select();
            $this->view->assign('user_list', $user_list);
            //查询任务类目
            $category_list =  TaskCategory::select();
            $this->view->assign('category_list', $category_list);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
 
        // 读取文本内容
        if(!empty($params['txt'])){
            $txt = file_get_contents($params['txt']);
            $txt = htmlspecialchars($txt);
            $title = explode('#标题',$txt);
            if(empty($title[1])){
                $this->error('任务模版标题格式错误');
            }
            $title = trim($title[1]);

            $content = explode('#内容',$txt);
            if(empty($content[1])){
                $this->error('任务模版内容格式错误');
            }
            $content_str = trim($content[1]);
            $content_str = str_replace("空格", "", $content_str);
            $content_str = str_replace("\r\n", " ", $content_str);
            $content_arr = explode(' ',$content_str);
            foreach ($content_arr as $k=>&$v) {
                $v = trim($v);
                if(!$v){
                    unset($content_arr[$k]);
                }
            }
            $value = explode('#变量',$txt);
            if(empty($value[1])){
                $this->error('任务模版变量格式错误');
            }
            $value = trim($value[1]);
            $value = str_replace("\r\n", "", $value);

            $value = explode('^',$value);
            $variate = [];
            foreach ($value as $k => &$v) {
                if($v){
                    if (strpos($v, $title) !== false) {
                        if(trim(str_replace($title, "", $v))){
                            $variate[] = [
                                'variate_name'=>$title,
                                'variate_value'=>trim(str_replace($title, "", $v))
                            ]; 
                        }
                        continue;
                    }
                    foreach ($content_arr as $ko=>$vo) {
                        if (strpos($v, $vo) !== false) {
                            if($vo && trim(str_replace($vo, "", $v))){
                                $variate[] = [
                                    'variate_name'=>$vo,
                                    'variate_value'=>trim(str_replace($vo, "", $v))
                                ];
                            }
                            unset($content_arr[$ko]);
                            break;
                        } 
                    }
                }
            }
            $params['title'] = $title;
            $content = trim($content[1]);
            $content = str_replace("空格", "", $content);
            $params['text'] = $content;
        }else{
            $variate_name = $params['variate_name'];
            $variate_value = $params['variate_value'];
            $variate = [];
            foreach ($variate_name as $k=>$v) {
                if($v && !empty($variate_value[$k])){
                    if(substr($variate_value[$k], -1) == '|'  ){
                        $variate_value[$k] = substr($variate_value[$k], 0, -1);
                    }
                    $variate[] = [
                        'variate_name'=>$v,
                        'variate_value'=>str_replace(' ','',$variate_value[$k])
                    ];
                }else{
                    $variate[] = [
                        'variate_name'=>'',
                        'variate_value'=>''
                    ];
                }
            }
        }
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $params['variate'] = json_encode($variate,JSON_UNESCAPED_UNICODE);
        unset($params['variate_name']);
        unset($params['variate_value']);
        unset($params['txt']);
        $params['add_time'] = time();
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = TaskTemplateModer::insert($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        
        $this->success();
    }
    /**
     * 编辑
     *
     * @return string
     * @throws \think\Exception
     */
    public function edit($ids = null){
        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        //查询任务类目
        $category_list =  TaskCategory::select();
        $this->view->assign('category_list', $category_list);
        $variate = json_decode($row['variate'],true);
        $this->view->assign("variate", $variate);
        $this->view->assign("row", $row);
		if ($this->request->isPost()) {
			$params = $this->request->post('row/a');

            
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $params = $this->preExcludeFields($params);

            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $params[$this->dataLimitField] = $this->auth->id;
            }

            // 读取文本内容
            if(!empty($params['txt'])){
                $txt = file_get_contents($params['txt']);
                $txt = htmlspecialchars($txt);
                $title = explode('#标题',$txt);
                if(empty($title[1])){
                    $this->error('任务模版标题格式错误');
                }
                $title = trim($title[1]);

                $content = explode('#内容',$txt);
                if(empty($content[1])){
                    $this->error('任务模版内容格式错误');
                }
                $content_str = trim($content[1]);
                $content_str = str_replace("空格", "", $content_str);
                $content_str = str_replace("\r\n", " ", $content_str);
                $content_arr = explode(' ',$content_str);
                foreach ($content_arr as $k=>&$v) {
                    $v = trim($v);
                    if(!$v){
                        unset($content_arr[$k]);
                    }
                }
                $value = explode('#变量',$txt);
                if(empty($value[1])){
                    $this->error('任务模版变量格式错误');
                }
                $value = trim($value[1]);
                $value = str_replace("\r\n", "", $value);
                $value = explode('^',$value);
                $variate = [];
                foreach ($value as $k => &$v) {
                    if($v){
                        if (strpos($v, $title) !== false) {
                            if(trim(str_replace($title, "", $v))){
                                $variate[] = [
                                    'variate_name'=>$title,
                                    'variate_value'=>trim(str_replace($title, "", $v))
                                ]; 
                            }
                            continue;
                        }
                        foreach ($content_arr as $ko=>$vo) {
                            if (strpos($v, $vo) !== false) {
                                if($vo && trim(str_replace($vo, "", $v))){
                                    $variate[] = [
                                        'variate_name'=>$vo,
                                        'variate_value'=>trim(str_replace($vo, "", $v))
                                    ];
                                }
                                unset($content_arr[$ko]);
                                break;
                            } 
                        }
                    }
                }
                $params['title'] = $title;
                $content = trim($content[1]);
                $content = str_replace("空格", "", $content);
                $params['text'] = $content;
            }else{
                $variate_name = $params['variate_name'];
                $variate_value = $params['variate_value']; 
               
                $variate = [];
                foreach ($variate_name as $k=>$v) {
                    if($v && !empty($variate_value[$k])){
                        
                        if(substr($variate_value[$k], -1) == '|'  ){
                            $variate_value[$k] = substr($variate_value[$k], 0, -1);
                        }
                        $variate[] = [
                            'variate_name'=>$v,
                            'variate_value'=> str_replace(' ','',$variate_value[$k])
                        ];
                    }else{
                        $variate[] = [
                            'variate_name'=>'',
                            'variate_value'=>''
                        ];
                    }
                }
            }
            $params['variate'] = json_encode($variate,JSON_UNESCAPED_UNICODE);
            unset($params['variate_name']);
            unset($params['variate_value']);
            unset($params['txt']);
            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                    $this->model->validateFailException()->validate($validate);
                }
                
                $result = $row->allowField(true)->save($params); 
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result === false) {
                $this->error(__('No rows were inserted'));
            }else{
                $this->success('操作成功');
            }
        }
		return $this->view->fetch();
	}

    



     /**
     * 发布模版任务
     *
     * @return string
     * @throws \think\Exception
     */
    public function send_task($ids = '')
    {
        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->redirect('DistributeTask/product_add');
            return;
            $this->error(__('No Results were found'));
        }
        $row['category_name'] = TaskCategory::where(['id'=>$row['category_id']])->value('name');   
        $this->view->assign("row", $row);
        if (false === $this->request->isPost()) {
            $type_arr = Shop::where(['status'=>1])->column('name');
            $this->view->assign('type_arr', $type_arr);
            $category_list = TaskCategoryList::select();
            $this->view->assign('category_list', $category_list);
            //查询所有的省
            $AreaList = Area::field("name")->where(['pid'=>0])->select();
            $this->view->assign('AreaList', $AreaList);
            return $this->view->fetch();
            
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $params['task_type'] = 1;
        //查询是录入的还是选择的
        if(!empty($params['category1'])){
            $chtegory_id = TaskCategoryList::insertGetId(['name'=>$params['category1'],'type'=>$params['type']]);
            unset($params['category1']);
            $params['category'] = $chtegory_id;
        }elseif(!empty($params['category'][0])){
            $params['category'] = $params['category'][0];
            unset($params['category1']);
        }else{
            $this->error('类目不可为空');
        }
        if(!empty($params['province'][0])){
            $params['province'] = $params['province'][0];
        }
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        if(!empty($params['zn_imgs'])){
            $params['imgs'] = $params['zn_imgs'];
        }


        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            //判断该模版类型
            if($row['type'] == 2){
                $category_name = explode(',',TaskCategory::where(['id'=>$row['category_id']])->value('chil_name'));
                if(!in_array($params['name'], $category_name)){
                    $this->error('该商品不在此类目关键词中,请确定模版选择是否正确');
                }
            }
            //判断该用户是否传了图片
            if($params['imgs']){
                $imgs = $params['imgs'];
                //传了图片则存入图片库内
                // $info = TaskImgs::where(['name'=>$params['name']])->find();
                // if($info){
                //     $imgs = $info['imgs'].','.$params['imgs'];
                // }else{
                //     $imgs = $params['imgs'];
                // }
                // TaskImgs::where(['id'=>$info['id']])->update(['imgs'=>$imgs]);
            }else{
                $this->error('未查询到该商品有图片,需要上传相对于图片才可发布');
                // $info = TaskImgs::where(['name'=>$params['name']])->find();
                // if(!$info){
                //     $this->error('未查询到该商品有图片,需要上传相对于图片才可发布');
                // }
                // $imgs = $info['imgs'];
            }
            //开始添加任务
            $imgs = explode(',',$imgs);
            if(count($imgs) < $params['num']){
                $this->error('图片数量不够');
            }
            
            if(!empty($params['yulan_title']) && !empty($params['yulan_content'])){
                //查询商户信息
                $shop  = Shop::where(['name'=>$params['type'],'status'=>1])->find();
                if($shop && $shop['is_admin_gl'] == 1){
                    foreach ($params['yulan_title'] as $k => $v) {
                        $title = $v;
                        $content = $params['yulan_content'][$k];
                        $replace = $this->replace($params,$title,$content);
                        $title = $replace['title'];
                        $content = $replace['content'];
                        $data = [
                            'title'=>$title,
                            'content'=>$content,
                            'imgs'=> $imgs[$k],
                            'beizhu'=>!empty($params['beizhu']) ? $params['beizhu'] : '',
                            'category'=>$params['category'],
                            'province'=>!empty($params['province']) ? $params['province'] : '',
                        ];
                        //商户上传任务操作
                        $shop  = Shop::where(['id'=>$shop['id']])->find();
                        $result = shop_add_task($data,$shop);
                        if ($result === false){
                            Db::commit();
                            $this->error('商户余额不足');
                        }
                    }
                }else{
                    foreach ($params['yulan_title'] as $k => $v) {
                        $title = $v;
                        $content = $params['yulan_content'][$k];
                        $replace = $this->replace($params,$title,$content);
                        $title = $replace['title'];
                        $content = $replace['content'];
                        
                        $arr = [
                            'add_time' => time(),
                            'title'=>$title,
                            'content'=>$content,
                            'status'=>-3,
                            'imgs'=> $imgs[$k],
                            'task_type'=>$params['task_type'] ? $params['task_type'] : 1,
                            'type'=>$params['type'] ,
                            'product_id'=>$params['product_id'] ,
                            'character_type'=> 1,
                            'category'=>$params['category'],
                            'beizhu'=>!empty($params['beizhu']) ? $params['beizhu'] : '',
                            'province'=>!empty($params['province']) ? $params['province'] : ''
                        ];
                        $result = DistributeTask::insert($arr);
                    }
                }
            }else{
                $variate = json_decode($row['variate'],true);

                $shop  = Shop::where(['name'=>$params['type'],'status'=>1])->find();
                if($shop && $shop['is_admin_gl'] == 1){
                    for ($i=0; $i < $params['num']; $i++) { 
                        $title = $row['title'];
                        $content = $row['text'];
                        foreach ($variate as $v) {
                            if($v['variate_name'] && $v['variate_value']){
                                $variate_value = explode('|',$v['variate_value']);
                                $content = str_replace($v['variate_name'],$variate_value[rand(0,count($variate_value)-1)],$content);
                                $title = str_replace($v['variate_name'],$variate_value[rand(0,count($variate_value)-1)],$title);
                            }
                        }
                        $replace = $this->replace($params,$title,$content);
                        $title = $replace['title'];
                        $content = $replace['content'];
    
                        $index = rand(0,count($imgs)-1);
                        $imgs_info = $imgs[$index];
                        unset($imgs[$index]);
                        sort($imgs);

                        $data = [
                            'title'=>$title,
                            'content'=>$content,
                            'imgs'=> $imgs_info,
                            'beizhu'=>!empty($params['beizhu']) ? $params['beizhu'] : '',
                            'category'=>$params['category'],
                            'province'=>!empty($params['province']) ? $params['province'] : '',
                        ];
                        //商户上传任务操作
                        $shop  = Shop::where(['id'=>$shop['id']])->find();
                        $result = shop_add_task($data,$shop);
                        if ($result === false){
                            Db::commit();
                            $this->error('商户余额不足');
                        }
                    }
                }else{
                    for ($i=0; $i < $params['num']; $i++) { 
                        $title = $row['title'];
                        $content = $row['text'];
                        foreach ($variate as $v) {
                            if($v['variate_name'] && $v['variate_value']){
                                $variate_value = explode('|',$v['variate_value']);
                                $content = str_replace($v['variate_name'],$variate_value[rand(0,count($variate_value)-1)],$content);
                                $title = str_replace($v['variate_name'],$variate_value[rand(0,count($variate_value)-1)],$title);
                            }
                        }
                        $replace = $this->replace($params,$title,$content);
                        $title = $replace['title'];
                        $content = $replace['content'];
    
                        $index = rand(0,count($imgs)-1);
                        $imgs_info = $imgs[$index];
                        unset($imgs[$index]);
                        sort($imgs);
                        $arr = [
                            'add_time' => time(),
                            'title'=>$title,
                            'content'=>$content,
                            'status'=>-3,
                            'imgs'=> $imgs_info,
                            'task_type'=>$params['task_type'] ? $params['task_type'] : 1,
                            'type'=>$params['type'] ,
                            'product_id'=>$params['product_id'] ,
                            'character_type'=> 1,
                            'category'=>$params['category'],
                            'beizhu'=>!empty($params['beizhu']) ? $params['beizhu'] : '',
                            'province'=>!empty($params['province']) ? $params['province'] : '',
                        ];
                        $result = DistributeTask::insert($arr);
                    }
                }
            }
            
            //TaskImgs::where(['id'=>$info['id']])->update(['imgs'=>implode(',',$imgs)]);
            
            // $list = User::where(['is_task_subscription'=>1])->select();
            // if($list){
            //     foreach ($list as $v) {
            //         $data = [
            //             "thing1"=>["value"=>'余享新任务已更新'],
            //             "time3"=>["value"=>date('Y-m-d H:i:s',time())]
            //         ];
            //         send_subscription($v['id'],'xF751UgAPsa4BajwBin-BU6lG1riuvJsNxNpIPGM28c','/subone/user/distribute_task',$data);
            //         User::where(['id'=>$v['id']])->update(['is_task_subscription'=>0]);
            //     }
            // }
            $this->model->where(['id'=>$row['id']])->update(['num'=>$row['num']+$params['num']]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    public function replace($params,$title,$content)
    {
        if(!empty($params['name'])){
            $content = str_replace('$name',$params['name'],$content);
            $title = str_replace('$name',$params['name'],$title);
        }
        if(!empty($params['brand'])){
            $content = str_replace('$brand',$params['brand'],$content);
            $title = str_replace('$brand',$params['brand'],$title);
        }
        if(!empty($params['location'])){
            $content = str_replace('$location',$params['location'],$content);
            $title = str_replace('$location',$params['location'],$title);
        }
        if(!empty($params['Size'])){
            $content = str_replace('$Size',$params['Size'],$content);
            $title = str_replace('$Size',$params['Size'],$title);
        }
        if(!empty($params['Type'])){
            $content = str_replace('$Type',$params['Type'],$content);
            $title = str_replace('$Type',$params['Type'],$title);
        }
        if(!empty($params['company'])){
            $content = str_replace('$company',$params['company'],$content);
            $title = str_replace('$company',$params['company'],$title);
        }
        if(!empty($params['role'])){
            $content = str_replace('$role',$params['role'],$content);
            $title = str_replace('$role',$params['role'],$title);
        }
        if(!empty($params['Intro1'])){
            $content = str_replace('$Intro1',$params['Intro1'],$content);
            $title = str_replace('$Intro1',$params['Intro1'],$title);
        }elseif(isset($params['Intro1'])){
            $content = str_replace('$Intro1','',$content);
            $title = str_replace('$Intro1','',$title);
        }
        if(!empty($params['Intro2'])){
            $content = str_replace('$Intro2',$params['Intro2'],$content);
            $title = str_replace('$Intro2',$params['Intro2'],$title);
        }elseif(isset($params['Intro2'])){
            $content = str_replace('$Intro2','',$content);
            $title = str_replace('$Intro2','',$title);
        }
        return ['title'=>$title,'content'=>$content];
    }
    /**
     * 生成预览文章
     */
    public function send_preview()
    {
        $params = $this->request->request();
        $row = $this->model->where('id',$params['id'])->find();
        $arr = [];
        $variate = json_decode($row['variate'],true);
        for ($i=0; $i < $params['num']; $i++) { 
            $title = $row['title'];
            $content = $row['text'];
            foreach ($variate as $v) {
                if($v['variate_name'] && $v['variate_value']){
                    $variate_value = explode('|',$v['variate_value']);
                    $content = str_replace($v['variate_name'],$variate_value[rand(0,count($variate_value)-1)],$content);
                    $title = str_replace($v['variate_name'],$variate_value[rand(0,count($variate_value)-1)],$title);
                }
            }
            $replace = $this->replace($params,$title,$content);
            $title = $replace['title'];
            $content = $replace['content'];

            $arr[] = [
                'title'=>$title,
                'content'=>$content,
            ];
        }
        $this->success($arr);

    }


    
}